#pragma once

#include "common.hpp"

const int defaultfd = -1;

class NamedPipe
{
public:
	NamedPipe(const std::string &name) : _name(name), _fd(defaultfd)
	{
	}
	bool Create()
	{
		// 1. 创建管道文件
		int n = mkfifo(fifoname.c_str(), mode);
		if (n == 0)
		{
			std::cout << "mkfifo success" << std::endl;
		}
		else
		{
			std::cout << "mkfifo failed" << std::endl;
			perror("mkfifo"); // 底层就是把错误码转变成错误描述
			return false;
		}
		return true;
	}
	void Close()
	{
		if (_fd == defaultfd)
			return;
		else
			close(_fd);
	}
	bool OpenForRead()
	{
		// 2. 打开文件，和普通文件没有区别
		// 命名管道操作特点：打开一端，在另一端没打开的时候，open会阻塞
		_fd = open(fifoname.c_str(), O_RDONLY);
		if (_fd < 0)
		{
			perror("open");
			return false;
		}
		std::cout << "open file success" << std::endl;
		return true;
	}
	bool OpenForWrite()
	{
		_fd = open(fifoname.c_str(), O_WRONLY);
		if (_fd < 0)
		{
			perror("open");
			return false;
		}
		return true;
	}
	// 输入参数：const &
	// 输出参数：*
	// 输入输出参数：&
	bool Read(std::string *out)
	{
		char buffer[SIZE] = {0}; // O(1)时间复杂度清空字符串
		ssize_t num = read(_fd, buffer, sizeof(buffer) - 1);
		if (num > 0)
		{
			buffer[num] = 0;
			*out = buffer;
		}
		else if (num == 0)
		{
			return false;
		}
		else
		{
			return false;
		}
		return true;
	}
	void Write(const std::string &in)
	{
		write(_fd, in.c_str(), in.size());
	}
	void Remove()
	{
		int m = unlink(fifoname.c_str());
		(void)m;
	}

	~NamedPipe()
	{
	}

private:
	// std::string path; // path + name;
	std::string _name;
	int _fd;
};